<!-- eslint-disable vue/multi-word-component-names -->
<script setup>
import { reactive, ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";

const router = useRouter();
const store = useStore();

const ruleFormRef = ref();

const checkName = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("Please input the password"));
  } else {
    if (ruleForm.checkPass !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value
        .validateField("checkPass")
        .then((res) => {
          console.log(res);
        })
        .catch((error) => {
          console.log("error", error);
        });
    }
    callback();
  }
};

const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("Please input the password"));
  } else {
    if (ruleForm.checkPass !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value
        .validateField("checkPass")
        .then((res) => {
          console.log(res);
        })
        .catch((error) => {
          console.log("error", error);
        });
    }
    callback();
  }
};

const ruleForm = reactive({
  password: "",
  username: "",
});

const rules = reactive({
  pass: [{ validator: validatePass, trigger: "blur" }],
  username: [{ validator: checkName, trigger: "blur" }],
});

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl
    .validate()
    .then(async (res) => {
      if (res) {
        await store.dispatch("user/login", ruleForm);
        // aewqq   123456
        router.push({ name: "home" });
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
};

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<template>
  <div class="register-box">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="账号名称" prop="username">
        <el-input v-model="ruleForm.username" />
      </el-form-item>

      <el-form-item label="密码" prop="pass">
        <el-input v-model="ruleForm.password" type="password" show-password />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          login
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">register</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style>
.register-box {
  max-width: 600px;
  margin: 100px auto 0;
}
</style>
